import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Logger;

public class TcpClient
{
    private Socket socketClient;
    Logger logger = MyLogger.getLogger();

    public void socketInitial()
    {
        try {
            socketClient = new Socket(InetAddress.getByName(Global.tcpServerIP), Global.tcpServerPort); //需要服务端先开启
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public StateObject receive()
    {
        try
        {
            ObjectInputStream objectInputStream = new ObjectInputStream(socketClient.getInputStream());
            try {
                //从服务器端读取状态信息
                //read state from server, very important.
                StateObject object = (StateObject)objectInputStream.readObject();
                //logger.info(object.toString());
                logger.info("Server client receive: " + object.toString());
                return object;
            }
            catch (ClassNotFoundException e)
            {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public void send(StateObject stateObject)
    {
        logger.info("Tcp client send: " + stateObject.toString());
        try
        {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socketClient.getOutputStream());
            objectOutputStream.writeObject(stateObject);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}